package com.piece.mall.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.support.response.Select;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.mall.model.PmsSkuInfo;
import com.piece.mall.service.*;
import com.piece.mall.vo.SkuInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = {"商品sku管理"})
@RequestMapping("/api/mall/sku/info")
public class PmsSkuInfoController extends FrameWorkController {

    @Resource
    private PmsBrandService pmsBrandService;

    @Resource
    private PmsCategoryService pmsCategoryService;

    @Resource
    private PmsSkuInfoService pmsSkuInfoService;

    @Resource
    private PmsSkuImagesService pmsSkuImagesService;

    @Resource
    private SmsSkuFullReductionService smsSkuFullReductionService;

    @Resource
    private PmsSpuInfoService pmsSpuInfoService;

    @PostMapping("/list")
    @ApiOperation(value = "查询sku列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = pmsSkuInfoService.findPage(queryTable);
        List tableData = dataTable.getData();
        List resultData = new ArrayList();
        for (Object object : tableData) {
            PmsSkuInfo skuInfo = (PmsSkuInfo) object;
            if (null != skuInfo.getBrandId()) {
                skuInfo.setBrandName(pmsBrandService.findNameById(skuInfo.getBrandId()));
            }
            if (null != skuInfo.getCatalogId()) {
                skuInfo.setCatalogName(pmsCategoryService.findNameById(skuInfo.getCatalogId()));
            }
            resultData.add(skuInfo);
        }
        return resultData;
    }

    @PostMapping("/table")
    @ApiOperation(value = "查询sku分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        Map<String, Object> params = queryTable.getParams();
        String keyParam = Convert.toString(params.get("Q_key_S_LK"));
        if (StringUtil.isNotEmpty(keyParam)) {
            params.remove("Q_key_S_LK");
            params.put("Q_skuName_S_LK_OR", keyParam);
            params.put("Q_skuTitle_S_LK_OR", keyParam);
            params.put("Q_skuSubtitle_S_LK_OR", keyParam);
            params.put("Q_skuDesc_S_LK_OR", keyParam);
        }
        DataTable dataTable = pmsSkuInfoService.findPage(queryTable);
        List tableData = dataTable.getData();
        List resultData = new ArrayList();
        for (Object object : tableData) {
            PmsSkuInfo skuInfo = (PmsSkuInfo) object;
            if (null != skuInfo.getBrandId()) {
                skuInfo.setBrandName(pmsBrandService.findNameById(skuInfo.getBrandId()));
            }
            if (null != skuInfo.getCatalogId()) {
                skuInfo.setCatalogName(pmsCategoryService.findNameById(skuInfo.getCatalogId()));
            }
            resultData.add(skuInfo);
        }
        dataTable.setData(resultData);
        return success(dataTable);
    }

    @PostMapping("/query/select")
    @ApiOperation(value = "查询sku下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "分页查询条件", dataTypeClass = Select.class, type = "body")
    })
    public AjaxResponse selectCustomQuery() {
        String selected = getRequest().getParameter("selected");
        QueryTable queryTable = initSelect("Q_skuName_S_LK,Q_skuTitle_S_LK");
        Map<String, Object> param = queryTable.getParams();
        param.put("sort", 1);
        queryTable.setParams(param);
        DataTable dataTable = pmsSkuInfoService.findPage(queryTable);
        if (StringUtil.isNotEmpty(selected)) {
            selected = FrameWorkConstants.SPLIT_PARAM + selected + FrameWorkConstants.SPLIT_PARAM;
        }
        return success(tableToSelect(dataTable, selected));
    }

    private Select tableToSelect(DataTable dataTable, String selected) {
        Select select = Select.builder().build();
        List<Object> tableData = dataTable.getData();
        List<Select.Entity> entityList = tableData.stream().map(data -> {
            PmsSkuInfo query = (PmsSkuInfo) data;
            return select.new Entity(Convert.toStr(query.getSkuId()), Convert.toStr(query.getSkuName()) + "[" + Convert.toStr(query.getSkuTitle()) + "]");
        }).filter(entity -> {
            if (StringUtil.isNotEmpty(selected)) {
                if (selected.indexOf(FrameWorkConstants.SPLIT_PARAM + entity.getId() + FrameWorkConstants.SPLIT_PARAM) != -1) {
                    return true;
                }
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        select.setTotal(dataTable.getRecordsTotal());
        select.setData(entityList);
        return select;
    }

    @GetMapping("/load")
    @AclPermission(code = "mall:product:edit")
    @ApiOperation(value = "加载sku表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        PmsSkuInfo pmsSkuInfo = new PmsSkuInfo();
        if (id != 0) {
            pmsSkuInfo = pmsSkuInfoService.findById(id);
        }
        return success(pmsSkuInfo);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "mall:product:edit")
    @ApiOperation(value = "保存sku表单数据")
    @ApiImplicitParam(value = "sku数据", dataTypeClass = PmsSkuInfo.class, type = "body")
    public AjaxResponse save() {
        PmsSkuInfo pmsSkuInfo;
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            if (null != id) {
                pmsSkuInfo = pmsSkuInfoService.findById(id);
            } else {
                pmsSkuInfo = new PmsSkuInfo();
            }
            initDB(pmsSkuInfo);
            pmsSkuInfoService.insertOrUpdate(pmsSkuInfo);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "mall:product:edit")
    @ApiOperation(value = "删除sku数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        pmsSkuInfoService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "mall:product:edit")
    @ApiOperation(value = "删除sku数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            pmsSkuInfoService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @PostMapping("/{skuId}/images")
    @ApiOperation(value = "查询sku图片列表")
    @ApiImplicitParam(name = "skuId", value = "skuId主键", type = "path")
    public List listSkuImages(@PathVariable Long skuId) {
        try {
            return pmsSkuImagesService.findImagesBySku(skuId);
        } catch (Exception e) {
            return new ArrayList();
        }
    }

    @SubmitPermission
    @PostMapping("/{skuId}/images/update")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "保存sku图片列表")
    @ApiImplicitParam(value = "sku数据", dataTypeClass = SkuInfoVo.class, type = "body")
    public AjaxResponse saveSkuImages(@RequestBody SkuInfoVo skuInfoVo) {
        try {
            pmsSkuImagesService.updateSkuImages(skuInfoVo);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @PostMapping("/{skuId}/price")
    @ApiOperation(value = "查询sku价格信息")
    @ApiImplicitParam(name = "skuId", value = "skuId主键", type = "path")
    public AjaxResponse listSkuPrice(@PathVariable Long skuId) {
        SkuInfoVo skuInfo = smsSkuFullReductionService.findSkuReduction(skuId);
        return success(skuInfo);
    }

    @SubmitPermission
    @PostMapping("/{skuId}/price/update")
    @AclPermission(code = "mall:product:spu")
    @ApiOperation(value = "保存sku价格信息")
    @ApiImplicitParam(value = "sku数据", dataTypeClass = SkuInfoVo.class, type = "body")
    public AjaxResponse saveSkuPrice(@RequestBody SkuInfoVo skuInfoVo) {
        try {
            smsSkuFullReductionService.saveSkuReduction(skuInfoVo);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @PostMapping("/{skuId}/detail")
    @ApiOperation(value = "查询sku详情")
    @ApiImplicitParam(name = "skuId", value = "skuId主键", type = "path")
    public AjaxResponse skuDetail(@PathVariable Long skuId) {
        try {
            Map result = pmsSkuInfoService.getSkuDetail(skuId);
            return success(result);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SERVER), e.getMessage());
        }
    }
}
